package comment

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"github.com/sirupsen/logrus"

	"chaoyer/ghost_assist/entity"
	"chaoyer/ghost_assist/Nets"
	"chaoyer/ghost_assist/base/code"
	"chaoyer/ghost_assist/utils"
	"chaoyer/ghost_assist/dao/commentdao"
	"chaoyer/ghost_assist/dao/visitordao"
)

// 插入一条评论
func AddComment(c *gin.Context) {

	postId := c.PostForm("postId")
	content := c.PostForm("content")
	commentId := c.PostForm("commentId")
	creator := c.PostForm("creator")
	if utils.IsBlank(postId, content, creator) {
		Nets.SendError(c, code.ARGS_NOT_ENOUGH)
		return
	}
	_, err := visitordao.FindByPostId(postId)
	if Nets.CheckError(c, err, "文章不存在") {
		return
	}

	var parent int
	if commentId != "" {
		// 父评论id
		var err error
		parent, err = strconv.Atoi(commentId)
		if err != nil {
			logrus.Error(err)
			Nets.SendError(c, code.ARGS_STATUS_ERROR)
			return
		}
	}
	// 构建
	var comment entity.Comment
	comment.PostId = postId
	comment.Content = content
	comment.Parent = parent
	comment.Creator = creator

	// 有父评论
	if parent != 0 {
		parent, err := commentdao.FindById(parent)
		if Nets.CheckError(c, err, "父评论不存在") {
			return
		}
		// 评论所属文章是否正确
		if parent.PostId != postId {
			logrus.Warnf("父评论所属文章不匹配,correct:%s  now:%s ", parent.PostId, postId)
			Nets.SendError(c, code.ARGS_STATUS_ERROR)
			return
		}
	}

	// 插入一条评论
	lastId, err := commentdao.Insert(comment)
	if err != nil {
		Nets.SendError(c, code.SEVER_ERROR)
		return
	}
	// 返回评论信息
	resData := treeSort(int(lastId))
	logrus.Info(resData)
	Nets.SendData(c, resData)
}

// 一篇文章的评论
func GetByPost(c *gin.Context) {
	postId := c.Query("postId")
	if utils.IsBlank(postId) {
		Nets.SendError(c, code.ARGS_NOT_ENOUGH)
		return
	}
	_, err := visitordao.FindByPostId(postId)
	if Nets.CheckError(c, err, "文章不存在") {
		return
	}
	comments, err := commentdao.FindByPost(postId)
	for i, _ := range comments {
		sort(&comments[i])
	}
	Nets.SendData(c, comments)
}

func treeSort(commentId int) *entity.Comment {

	if commentId == 0 {
		return nil
	}
	// 获取该评论最顶级的评论
	commentTop := top(commentId)

	// 排列整个评论树
	sort(commentTop)

	return commentTop;
}

// 获取该评论最顶级的评论
func top(commentId int) *entity.Comment {
	comment, _ := commentdao.FindById(commentId)
	if comment.Parent == 0 {
		return &comment
	}
	return top(comment.Parent)
}

// 排列整个评论树
func sort(comment *entity.Comment) {
	comments, _ := commentdao.FindByParent(comment.ID)
	comment.ChildComments = comments // 子评论
	for i, _ := range comments {
		sort(&comments[i])
	}
}
